const db = require('../config/db');
const { success, fail } = require('../utils/response');

exports.getCart = async (req, res) => {
  const [rows] = await db.query(`
    SELECT Cart.*, Product.name, Product.price, Product.image 
    FROM Cart 
    JOIN Product ON Cart.product_id = Product.id 
    WHERE Cart.user_id=?
  `, [req.user.id]);
  res.json(success(rows));
};

exports.addToCart = async (req, res) => {
  const { product_id, quantity } = req.body;

  // 查完整商品信息
  const [productRows] = await db.query(
    'SELECT id, name, image, price FROM Product WHERE id=?',
    [product_id]
  );
  if (!productRows.length) return res.json(fail('商品不存在'));

  const product = productRows[0];

  // 同用户+同商品唯一，重复添加时数量累加
  await db.query(
    'INSERT INTO Cart (user_id, product_id, quantity, product_name, product_image, price) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE quantity = quantity + VALUES(quantity)',
    [req.user.id, product_id, quantity, product.name, product.image, product.price]
  );

  res.json(success());
};

exports.updateCartItem = async (req, res) => {
  const { id } = req.params;
  const { quantity } = req.body;
  
  const [rows] = await db.query('SELECT id FROM cart WHERE id=? AND user_id=?', [id, req.user.id]);
  if (!rows.length) return res.json(fail('购物车项不存在'));
  
  await db.query('UPDATE cart SET quantity=? WHERE id=?', [quantity, id]);
  res.json(success());
};

exports.removeFromCart = async (req, res) => {
  const { id } = req.params;
  const [result] = await db.query('DELETE FROM cart WHERE id=? AND user_id=?', [id, req.user.id]);
  if (result.affectedRows === 0) return res.json(fail('购物车项不存在'));
  res.json(success());
};

exports.clearCart = async (req, res) => {
  await db.query('DELETE FROM cart WHERE user_id=?', [req.user.id]);
  res.json(success());
};